# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
moment  = require 'moment'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 查询主机配置
    await client.query \
        "select count(*) as count from pay_hosts", defer err, result
    if err then done(client); return next(err)
    res.locals.n_hosts = result.rows[0].count

    # 查询总交易笔数
    await client.query \
        "select count(uuid) as count from
            (select distinct uuid from pay_trlist
                where sys_time > CURRENT_DATE) as temp", defer err, result
    if err then done(client); return next(err)
    res.locals.total_cnt = result.rows[0].count

    # 查询异常交易笔数
    await client.query \
        "select count(uuid) as count from
            (select distinct uuid from pay_trlist
                where sys_time > CURRENT_DATE and status = 1)
            as temp", defer err, result
    if err then done(client); return next(err)
    res.locals.abnormay_cnt = result.rows[0].count

    # 查询响应码不为成功的交易笔数
    await client.query \
        "select count(uuid) as count from
            (select distinct uuid from pay_trlist
                where sys_time > CURRENT_DATE and
                chnl = 1 and
                json_extract_path_text(o_pkt, '39') <> '00')
            as temp", defer err, result
    if err then done(client); return next(err)
    res.locals.bad_cnt = result.rows[0].count

    # 查询清算类交易笔数
    await client.query \
        "select count(uuid) as count from
            (select distinct uuid from pay_trlist
                where sys_time > CURRENT_DATE and
                json_extract_path_text(trinfo, 'settl') = 'true')
            as temp", defer err, result
    if err then done(client); return next(err)
    res.locals.settl_cnt = result.rows[0].count
    res.locals.settl_rate =
        ((res.locals.settl_cnt * 100) / res.locals.total_cnt).toFixed(2)

    # 查询第一笔交易发生时间
    await client.query \
        "select sys_time from pay_trlist
            where sys_time > CURRENT_DATE
            order by sys_time limit 1", defer err, result
    if err then done(client); return next(err)
    if result.rows.length > 0
        res.locals.first_trans_time = result.rows[0].sys_time.format("HH 点 mm 分")
    else
        res.locals.first_trans_time = 'NaN'

    # 查询交易峰值时间及笔数
    await client.query \
        "select date_trunc('minute', sys_time) as minute,
            count(distinct uuid) as count from pay_trlist
            where sys_time > CURRENT_DATE
            group by minute
            order by count desc limit 1", defer err, result
    if err then done(client); return next(err)
    if result.rows.length > 0
        res.locals.max_trans_cnt = result.rows[0].count
        res.locals.max_trans_time = result.rows[0].minute.format('HH 点 mm 分')
    else
        res.locals.max_trans_cnt = 0
        res.locals.max_trans_time = 'NaN'
    done()
    res.render 'index'


router.post '/index/rundata', (req, res, next) ->
    res.type 'json'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 查询全部交易
    await client.query \
        "select date_trunc('minute', sys_time) as minute,
            count(distinct uuid) as count from pay_trlist
        where sys_time > CURRENT_DATE
        group by minute
        order by minute", defer err, result
    if err then done(client); return next(err)

    all_data = []
    for record in result.rows
        all_data.push value: [
            record.minute.format('YYYY-MM-DD HH:mm:ss'), record.count
        ]

    # 查询清算类交易
    await client.query \
        "select date_trunc('minute', sys_time) as minute,
            count(distinct uuid) as count from pay_trlist
        where sys_time > CURRENT_DATE and
        json_extract_path_text(trinfo, 'settl') = 'true'
        group by minute
        order by minute", defer err, result
    if err then done(client); return next(err)

    settl_data = []
    for record in result.rows
        settl_data.push value: [
            record.minute.format('YYYY-MM-DD HH:mm:ss'), record.count
        ]

    # 查询失败交易
    await client.query \
        "select date_trunc('minute', sys_time) as minute,
            count(distinct uuid) as count from pay_trlist
        where sys_time > CURRENT_DATE and
        json_extract_path_text(trinfo, 'settl') = 'true' and
            (status = 1 or
            case chnl
                when 1 then json_extract_path_text(o_pkt, '39') <> '00'
                when 2 then json_extract_path_text(o_pkt, '39') <> '00'
                when 3 then json_extract_path_text(o_pkt, 'respCode') <> '00'
            end)
        group by minute
        order by minute", defer err, result
    if err then done(client); return next(err)
    done()

    error_data = []
    for record in result.rows
        error_data.push value: [
            record.minute.format('YYYY-MM-DD HH:mm:ss'), record.count
        ]

    # 如果没有数据或数据不足，则插入一些无意义的值
    if all_data.length < 2
        all_data.push value: [ moment().format('YYYY-MM-DD 00:00:01'), 0 ]
    if all_data.length < 2
        all_data.push value: [ moment().format('YYYY-MM-DD HH:mm:ss'), 0 ]

    # 填充空白节点
    for item, i in all_data
        time = item.value[0]
        found = false
        for item2, j in settl_data
            if item2.value[0] == time
                found = true
                break
        if not found then settl_data.push value: [ time, 0 ]
    # 必须按时间排序
    settl_data.sort (a, b) ->
        return 1 if a.value[0] > b.value[0]
        return -1 if a.value[0] < b.value[0]
        return 0

    # 填充空白节点
    for item, i in all_data
        time = item.value[0]
        found = false
        for item2, j in error_data
            if item2.value[0] == time
                found = true
                break
        if not found then error_data.push value: [ time, 0 ]
    # 必须按时间排序
    error_data.sort (a, b) ->
        return 1 if a.value[0] > b.value[0]
        return -1 if a.value[0] < b.value[0]
        return 0

    return res.json
        succ: true,
        all_data: all_data,
        settl_data: settl_data,
        error_data: error_data
